<script lang="ts" setup>
import { ref, watch, reactive } from 'vue'
import { mStyles } from "@/utils/useStyles";
import { useRoute } from 'vue-router';
import { requestToast } from "@/utils/requestToast";
import API from "@/service/api/order";
import { useDynamicKeepAlive } from '@/utils/keepAliveUtils'
import { truncateText } from "@/utils/ellipsis";

// 1. 定义接口类型
interface OrderPart {
    further_parts?: FormConfigItem[];
    title?: string;
}

interface FormConfigItem {
    part_key: string;
    part_name: string;
    part_type: number;
    [key: string]: any; // 其他可能的属性
}

interface DynamicFormInstance {
    validate: (field?: FormConfigItem) => boolean;
    getFormData: () => Record<string, any>;
}

interface FormData {
    order_num: string | undefined;
    order_parts: Array<{
        part_key: string;
        part_name: string;
        part_value: string;
        pic_value: string[] | null;
    }>;
    [key: string]: any; // 动态字段
}

// 2. 路由和属性定义
const mRoute = useRoute();
const props = defineProps<{
    orderPart: OrderPart;
    mFurTitle: object;
}>();

// 3. 表单数据和引用定义
const mformData = reactive<FormData>({
    order_num: mRoute.query.order_num as string,
    order_parts: [],
});

const mDynamicFormRef = ref<any | null>(null);
const mActionSheetRef = ref<{ openDialog: () => void; closeDialog: () => void } | null>(null);
const mFormConfig = ref<FormConfigItem[]>([]);
const mSubmit = ref(true);

// 4. 方法实现
const openDialog = async (): Promise<void> => {
    if (mActionSheetRef.value) {
        mActionSheetRef.value.openDialog();
        mFormConfig.value = props.orderPart.further_parts ?? [];
        clkDynamicsValidateForm();
    }
};

const clkDynamicsValidateForm = (): boolean => {
    let isValid = true;

    if (Array.isArray(mFormConfig.value) && mFormConfig.value.length > 0 && mDynamicFormRef.value) {
        mFormConfig.value.forEach(field => {
            if (!mDynamicFormRef.value!.validate(field)) {
                isValid = false;
            }
        });
    }

    return isValid;
};

const emit = defineEmits(['is-Confirm'])
const { removeCachedView } = useDynamicKeepAlive()
const clkOrderData = async () => {
    if (clkDynamicsValidateForm()) {

        const dynamicFields = mDynamicFormRef.value.getFormData();

        // 清除动态字段
        if (Array.isArray(mFormConfig.value)) {
            mFormConfig.value.forEach(field => {
                if (field.part_key in mformData) {
                    delete mformData[field.part_key];
                }
            });
        }

        const submitData = {
            ...mformData,
            ...dynamicFields
        };

        submitData.order_parts = Array.isArray(mFormConfig.value) ? mFormConfig.value.map(field => ({
            part_key: field.part_key,
            part_name: field.part_name,
            part_value: field.part_type !== 3 ? (submitData[field.part_key] || '') : '',
            pic_value: field.part_type === 3 ?
                (submitData[field.part_key]?.map((item: { path: string }) => item.path) || []) : null
        })) : [];


        const { status } = await requestToast(submitData, API.orderFurtherData, "补充成功")
        if (status) {
            //通知列表页刷新
            removeCachedView('', 'order')
            if (mActionSheetRef.value) {
                mActionSheetRef.value.closeDialog();
                emit('is-Confirm');
            }
        }
    }
};

// 5. 监听器
watch(
    () => clkDynamicsValidateForm(),
    (isValid) => {
        mSubmit.value = !isValid;
    },
    { deep: true }
);


//获取补充资料的回复内容
const getOrderFurtherPart = () => {
    // 检查order_logs是否存在
    if (!props.mFurTitle) {
        console.error('mOrderDetail.order_logs is undefined or null');
        return '';
    }

    // 确保order_logs是数组
    const logs = Array.isArray(props.mFurTitle)
        ? props.mFurTitle
        : Object.values(props.mFurTitle);

    // 检查logs是否为空
    if (logs.length === 0) {
        console.error('No logs found in mOrderDetail.order_logs');
        return '';
    }

    // 遍历logs查找有效的content
    for (const item of logs) {
        // 检查item是否存在content属性
        if (!item.content) continue;

        // 检查content是否为数组且有元素
        if (Array.isArray(item.content) && item.content.length > 0) {
            // 检查第一个content项是否有part_value
            if (item.content[0] && item.content[0].part_value) {
                return item.content[0].part_value;
            }
        }
    }
    // 如果没有找到有效的part_value
    return '';
};



defineExpose({ openDialog });
</script>

<template>
    <cVanActionSheet ref="mActionSheetRef" :iClose="false" :iButton="false" class="gr-add" :orderPart="orderPart"
        iBgColor="#F6F6F6" iPadding="0px 15px 20px 15px">
        <div class="gr-add-form">
            <div class="gr-nav">
                <van-icon name="arrow-left" size="5vmin" @click="mActionSheetRef?.closeDialog();" />
                <span class="gr-add-title">
                    补充资料
                </span>
                <cButton iLinearGradien :iColor="mStyles?.color10" class="w-[150px] h-auto" @click="clkOrderData"
                    iHeight="7.622vmin" iPadding="0px" round :disabled="mSubmit">提交
                </cButton>
            </div>
            <div class="custom-body">
                <p>{{ getOrderFurtherPart() }}</p>
                <div class="form">
                    <cDynamicForm :formConfig="mFormConfig" ref="mDynamicFormRef" />
                </div>
            </div>
        </div>
    </cVanActionSheet>
</template>

<style lang="scss" scoped>
.custom-body {
    padding-top:130px;
    max-height:1000px;
    flex: 1;
    overflow-y: auto;
}

.gr-add-title {
    font-size: 34px;
    font-weight: 500;
    text-align: center;
    padding: 15px;
    border-radius: 10px;
}

.gr-add-form {
    text-align: left;

    p {
        width: 100%;
        background: #F5E9E0;
        border-radius: 24px;
        padding: 25px;
        margin-bottom: 30px;
        word-break: break-all;
        color: #EB731D;
    }

    position: relative;
}
:deep(.van-action-sheet__content){
    overflow: hidden;
}

.gr-nav {
    display: flex;
    position: absolute;
    height:110px;
    top: 0;
    left: 0;
    right: 0;
    width: 100%;
    flex-shrink: 0;
    z-index:999;
    background: rgb(246, 246, 246);
    justify-content: space-between;
    align-items: center;
}

:deep(.van-action-sheet__content) {
    overflow-y: hidden;
}
</style>